<template>
  <div class="wellness-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>养生内容管理</span>
          <div class="header-actions">
            <el-input
              v-model="searchQuery"
              placeholder="搜索内容..."
              style="width: 200px; margin-right: 16px"
              clearable
              @clear="fetchArticles"
            />
            <el-select 
              v-model="categoryFilter" 
              placeholder="分类筛选" 
              clearable
              @clear="fetchArticles"
              style="width: 150px; margin-right: 16px"
            >
              <el-option label="食疗养生" value="食疗养生" />
              <el-option label="节气养生" value="节气养生" />
              <el-option label="自我保健" value="自我保健" />
            </el-select>
            <el-button type="primary" @click="handleAdd">添加内容</el-button>
          </div>
        </div>
      </template>

      <el-table :data="contents" style="width: 100%" v-loading="loading">
        <el-table-column prop="articleId" label="ID" width="80" />
        <el-table-column prop="title" label="标题" width="200" />
        <el-table-column prop="type" label="分类" width="120" />
        <el-table-column prop="authorName" label="作者" width="120" />
        <el-table-column prop="publishTime" label="发布时间" width="180" />
        <el-table-column prop="views" label="浏览量" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 内容编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加内容' : '编辑内容'"
      width="800px"
    >
      <el-form 
        ref="formRef"
        :model="contentForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="标题">
          <el-input v-model="contentForm.title" />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="contentForm.type">
            <el-option label="食疗养生" value="食疗养生" />
            <el-option label="节气养生" value="节气养生" />
            <el-option label="自我保健" value="自我保健" />
          </el-select>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="contentForm.authorName" />
        </el-form-item>
        <el-form-item label="内容">
          <el-input 
            v-model="contentForm.content" 
            type="textarea" 
            rows="10"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="contentForm.status">
            <el-option label="已发布" value="已发布" />
            <el-option label="草稿" value="草稿" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getArticleList, addArticle, updateArticle, deleteArticle } from '@/api/healthArticle'

const formRef = ref(null)
const searchQuery = ref('')
const categoryFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)
const dialogVisible = ref(false)
const dialogType = ref('add')
const contentForm = ref({
  title: '',
  type: '',
  authorName: '',
  content: '',
  status: '草稿'
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  authorName: [
    { required: true, message: '请输入作者', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' }
  ]
}

const contents = ref([])
const loading = ref(false)

const fetchArticles = async () => {
  loading.value = true
  try {
    const response = await getArticleList({
      page: currentPage.value,
      size: pageSize.value,
      keyword: searchQuery.value,
      type: categoryFilter.value || undefined
    })
    if (response.code === 200) {
      contents.value = response.data.list
      total.value = response.data.total
    } else {
      ElMessage.error(response.message || '获取列表失败')
    }
  } catch (error) {
    console.error('获取文章列表失败:', error)
    ElMessage.error('获取列表失败')
  } finally {
    loading.value = false
  }
}

const getStatusType = (status) => {
  const types = {
    '已发布': 'success',
    '草稿': 'info'
  }
  return types[status] || ''
}

const handleAdd = () => {
  dialogType.value = 'add'
  contentForm.value = {
    title: '',
    type: '',
    authorName: '',
    content: '',
    status: '草稿'
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  contentForm.value = { ...row }
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该文章吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await deleteArticle(row.articleId)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchArticles()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
  } catch (error) {
    return
  }
  
  try {
    const api = dialogType.value === 'add' ? addArticle : updateArticle
    const response = await api(contentForm.value)
    if (response.code === 200) {
      ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功')
      dialogVisible.value = false
      fetchArticles()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchArticles()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchArticles()
}

// 监听搜索条件变化
watch([searchQuery, categoryFilter], () => {
  currentPage.value = 1  // 重置页码
  fetchArticles()
})

onMounted(() => {
  fetchArticles()
})
</script>

<style scoped>
.wellness-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style> 